<?php
/**
 * ################################################
 * #【Description】 认证接口，用户小程序身份认证
 * #【Author】 akon
 * #【Date】 2017年6月5日
 * ################################################
 */
namespace Shx\Controller;
use Think\Controller;

class AuthController extends Controller {
    /**
     * 保存登录用户信息
     */
    public function saveUserInfo() {
        $userInfo = I('userInfo');
        $openId   = I('openId');
        $session  = I('session');

        $userInfo = json_decode(htmlspecialchars_decode($userInfo),true);  //将用户信息转换为数组
        //查询数据表中是否有此用户
        $res = M('user')->where(array('open_id'=>$openId))->count();
        if(!$res){
            $info = array(
                'user_id'   => $userInfo['user_id'],
                'open_id'   => $openId,
                'nickname'  => $userInfo['nickName'],
                'avatarUrl' => $userInfo['avatarUrl'],
                'user_session' => $session,
                'login_time'=> date('Y-m-d H:i:s', time()),
            );
            $id = M('user')->data($info)->add();
            if($id){
                echo $id;
            }
        }else{
            echo '用户已存在'.$openId;
        }

    }


    /**
     * 解密openId
     * 1、获取code
     * 2、code换取session_key
     * 3、
     */
    public function getOpenId() {
        $receive = I('get.');
        $user_info = json_decode(htmlspecialchars_decode($receive['userInfo']),true);
        $session_key_url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.C('APPID').'&secret='.C('APPSECRET').'&js_code='.$receive['code'].'&grant_type=authorization_code';
        $openId          = _curl($session_key_url);
        //查询数据表中是否有此用户
        $is_user_id = M('users')->where(array('openid'=>$openId['openid']))->field('user_id')->find();
        //生成session，用于用户身份唯一性识别
        $session_key   = takeUniqueStr();
        $session_value = $openId['session_key'];
        session(
            array(
                'name'  =>$session_key,
                'expire'=>time() + 2160000
            ),
            $session_value
        );
        session($session_key,$session_value,time()+2160000);
        //用户信息存储
        if(!$is_user_id) {
            $user_data = array(
                'openid' => $openId[ 'openid' ],
                'nickname' => $user_info[ 'nickName' ],
                'avatarUrl' => $user_info[ 'avatarUrl' ],
                'sex' => $user_info[ 'gender' ],
                'reg_time' => time(),
                'last_login' => time(),
                'province' => $user_info[ 'province' ],
                'city' => $user_info[ 'city' ],
                'country' => $user_info[ 'country' ],
                'avataUrl' => $user_info[ 'avataUrl' ]
            );
            $user_id = M( 'users' )->add( $user_data );
        }else{
            M('users')->where(array('last_login'=>time()))->setField('last_login',time());
        }
        if($openId){
            $res = array(
                'status'        => 1,
                'openId'        => $openId['openid'],
                'session_id'    => $session_key,
                'sess'          => session($session_key),
                'user_id'      => $is_user_id['user_id']
            );
        }else{
            $res = array(
                'status' => 0
            );
        }

        exit(json_encode($res));
    }

    /**
     * 判断登录状态
     */
    public function getLoginStatus() {
        $session_key = I('get.key');
        $session_value = I('get.value');
        $time = I('get._time');
    }

    /**
     * 微信支付获取openid
     */
    public function getPayOpenId(){
        $receive = json_decode(file_get_contents('php://input'),true);
        if(!$receive){
            $res = array(
                'status' => 0,
                'msg'    => '数据异常，请退出重试'
            );
            exit(json_encode($res, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
        }
        $open_id = M('users')->where(array('user_id'=>$receive['user_id']))->field('openid')->find();
        if(!$open_id){
            $res = array(
                'status' => 0,
                'msg'    => '数据异常，请退出重试'
            );
            exit(json_encode($res, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
        }

        $res = array(
            'status'  => 1,
            'open_id' => $open_id['openid']
        );
        exit(json_encode($res, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
    }

    /**
     * 记录用户登录日志
     */
    public function takeUserLogin() {
        $receive = json_decode(file_get_contents('php://input'),true);
        $arr = array(
            'user_id' => $receive['user_id'],
            'scene'   => getSceneValue($receive['scene']),
            'access_path' => $receive['path']
        );
        $res = M('user_log')->add($arr);
        if($res){
            exit(json_encode(array('status'=>1)));
        }
    }

}